#!/bin/bash

# ============================================
# Vue3 + Vite 前端项目部署脚本
# ============================================

set -e  # 遇到错误立即退出

# 颜色输出
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

# 配置变量（请根据实际情况修改）
SERVER_USER="root"
SERVER_IP="10.170.129.4"
SERVER_PATH="/var/www/frontend"
LOCAL_BUILD_PATH="./web/dist"
NGINX_CONF_PATH="./deploy/nginx/frontend.conf"
NGINX_SERVER_CONF_PATH="/etc/nginx/conf.d/frontend.conf"

# 提示信息
echo_info() {
    echo -e "${GREEN}[INFO]${NC} $1"
}

echo_warn() {
    echo -e "${YELLOW}[WARN]${NC} $1"
}

echo_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# 检查命令是否存在
check_command() {
    if ! command -v $1 &> /dev/null; then
        echo_error "$1 未安装，请先安装"
        exit 1
    fi
}

# 步骤1：检查环境
echo_info "步骤1: 检查环境..."
check_command "npm"
check_command "rsync"

# 步骤2：构建项目
echo_info "步骤2: 构建项目..."
cd web

if [ ! -f ".env.production" ]; then
    echo_warn ".env.production 文件不存在，正在创建..."
    cat > .env.production << EOF
VITE_API_URL=http://10.170.129.4:8000/
VITE_PUBLIC_PATH=/
VITE_PORT=3000
VITE_DIST_PATH=dist
EOF
    echo_warn "请编辑 .env.production 文件设置正确的 API 地址"
fi

echo_info "安装依赖..."
npm install

echo_info "开始构建..."
npm run build

if [ $? -ne 0 ]; then
    echo_error "构建失败！"
    exit 1
fi

if [ ! -d "dist" ]; then
    echo_error "构建目录 dist 不存在！"
    exit 1
fi

echo_info "构建完成！"

# 步骤3：上传文件
echo_info "步骤3: 上传文件到服务器..."
cd ..

echo_info "创建服务器目录..."
ssh $SERVER_USER@$SERVER_IP "mkdir -p $SERVER_PATH"

echo_info "上传文件..."
rsync -avz --delete --progress \
    --exclude '*.map' \
    $LOCAL_BUILD_PATH/ $SERVER_USER@$SERVER_IP:$SERVER_PATH/

if [ $? -ne 0 ]; then
    echo_error "文件上传失败！"
    exit 1
fi

echo_info "文件上传完成！"

# 步骤4：配置 Nginx
echo_info "步骤4: 配置 Nginx..."
echo_warn "请手动执行以下命令配置 Nginx:"
echo "1. 将配置文件复制到服务器:"
echo "   scp $NGINX_CONF_PATH $SERVER_USER@$SERVER_IP:$NGINX_SERVER_CONF_PATH"
echo ""
echo "2. SSH 登录服务器并执行:"
echo "   ssh $SERVER_USER@$SERVER_IP"
echo "   sudo nginx -t"
echo "   sudo systemctl reload nginx"

# 步骤5：完成
echo_info "============================================"
echo_info "部署完成！"
echo_info "============================================"
echo_info "前端地址: http://$SERVER_IP"
echo_info "服务器路径: $SERVER_PATH"
echo_info "============================================"

